package com.wut.core.config.adapter;

import cn.hutool.core.util.StrUtil;
import com.wut.core.common.enums.ResponseMessageEnum;
import com.wut.core.common.vo.BaseResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class WebAbstractResponseAdapter implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    /**
     * 拦截请求返回值,根据请求类型自动填充返回值
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response) {

        if (body instanceof BaseResponse && StrUtil.isEmpty(((BaseResponse<?>) body).getMessage())) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            body = BaseResponse.SUCCESS(ResponseMessageEnum.getRespMessage(req.getMethod()) + "成功", ((BaseResponse<?>) body).getData());
        }
        return body;
    }
}